# some common methods for entity

from entity import Data
from entity import Segment
from datetime import datetime
from google.appengine.ext import db


# format list of Data to output
def jsonDataAsList(data,tzoffset):
  s = "([";
  s = s + data.__str__(tzoffset)
  s = s + "])" 
  return s;


# format list of Data to output
def jsonListData(list,tzoffset):
  s = "([";
  for data in list:
    s = s + data.__str__(tzoffset) + ","
  if "," in s:
    s = s[0:len(s)-1]
  s = s + "])" 
  return s;
  
  
  
# list all data
def listAllData(tzoffset):
  results = Data.all().order("datetime")
  
  return jsonListData(results,tzoffset)


# list specific data with "id"
def listDataById(id,tzoffset):
  buildDataById(id)
  results = Data.all().filter("uuid =",id)
  
  return jsonListData(results,tzoffset)
     
     

# build all data
def buildAllData():
  while Segment.all().count() != 0:   
     segment = Segment.all().fetch(1)[0]
     if segment.datetime is not None:
       buildDataById(segment.uuid)

      

# build spec data
def buildDataById(uuid):
  results = Segment.all().filter("uuid =",uuid).order("seq")

  if results.count() == 0:
     return None
  else:
     data = Data(uuid=uuid,content="")
     for segment in results:
        data.content = data.content + segment.content
        data.datetime = segment.datetime
     data.put()
     delSegmentById(uuid)
     return data

# delete spec segment with "uuid"
def delSegmentById(uuid):
  results = Segment.all().filter("uuid =",uuid)
  count = results.count()
  
  if count != 0:
     db.delete(results)
  return count
     

 